import boto3

AWS_REGION_NAME = 'cn-north-1'
AWS_S3_ACCESS_KEY_ID = "AKIATOULZOMS6E5QEMKM"
AWS_S3_SECRET_ACCESS_KEY = "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"
AWS_S3_BUCKET_NAME = 'designorder'


class S3StoryOperate(object):
    def __init__(self):
        try:
            session = boto3.session.Session(aws_access_key_id=AWS_S3_ACCESS_KEY_ID,
                                            aws_secret_access_key=AWS_S3_SECRET_ACCESS_KEY,
                                            region_name=AWS_REGION_NAME)
            self.bucket_name = AWS_S3_BUCKET_NAME
            self.resource = session.resource('s3', AWS_REGION_NAME)

        except Exception as ex:
            print(ex)
            exit(ex)

    def get_all_key(self, bucket_name):
        keys = []
        for obj in self.resource.Bucket(bucket_name).objects.all():
            keys.append(obj.key)
        return keys

    def upload_file(self, upload_path, data):
        try:
            self.resource.Bucket(self.bucket_name).put_object(Key=upload_path, Body=data)
        except Exception as ex:
            print(ex)
            exit(ex)

    def download_file(self, key, download_path):
        try:
            self.resource.Bucket(self.bucket_name).download_file(key, download_path)
        except Exception as ex:
            print(ex)
            exit(ex)


if __name__ == "__main__":
    s3 = S3StoryOperate()
    # data = open(r'D:\Pycharm_Project\do_design_web\do_design_web_ai_recommend\ai_recommend\app_recommend.py', 'rb')
    # s3.upload_file('app.py', data)
    s3.download_file('DO-Design_Test/app.py', 'app.py')
